package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.service.PermissionService;
import com.example.demo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 测试控制器
 * 用于系统诊断和测试
 */
@RestController
@RequestMapping("/api/test")
public class TestController {
    
    private static final Logger log = LoggerFactory.getLogger(TestController.class);
    
    private final UserService userService;
    private final PermissionService permissionService;
    
    public TestController(UserService userService, PermissionService permissionService) {
        this.userService = userService;
        this.permissionService = permissionService;
    }
    
    /**
     * 系统状态检查
     */
    @GetMapping("/system-status")
    public Result<Map<String, Object>> getSystemStatus() {
        log.info("检查系统状态");
        
        Map<String, Object> status = new HashMap<>();
        
        try {
            // 检查数据库连接
            status.put("database", "connected");
            
            // 检查权限表是否存在和有数据
            List<String> adminRoles = permissionService.getUserRoleCodes(1L);
            List<String> adminPermissions = permissionService.getUserPermissionCodes(1L);
            
            status.put("permissionTablesExist", true);
            status.put("adminRoleCount", adminRoles.size());
            status.put("adminPermissionCount", adminPermissions.size());
            status.put("adminRoles", adminRoles);
            
            if (adminRoles.isEmpty()) {
                status.put("warning", "权限数据库表可能未初始化");
            }
            
        } catch (Exception e) {
            log.error("系统状态检查失败", e);
            status.put("database", "error");
            status.put("error", e.getMessage());
            status.put("warning", "权限数据库表可能不存在，请执行初始化脚本");
        }
        
        return Result.success("系统状态检查完成", status);
    }
    
    /**
     * 测试用户权限
     */
    @GetMapping("/user-permissions/{userId}")
    public Result<Map<String, Object>> getUserPermissions(@PathVariable Long userId) {
        log.info("检查用户{}的权限", userId);
        
        Map<String, Object> userInfo = new HashMap<>();
        
        try {
            List<String> roles = permissionService.getUserRoleCodes(userId);
            List<String> permissions = permissionService.getUserPermissionCodes(userId);
            
            userInfo.put("userId", userId);
            userInfo.put("roles", roles);
            userInfo.put("permissions", permissions);
            userInfo.put("roleCount", roles.size());
            userInfo.put("permissionCount", permissions.size());
            
        } catch (Exception e) {
            log.error("获取用户权限失败", e);
            userInfo.put("error", e.getMessage());
        }
        
        return Result.success("用户权限信息", userInfo);
    }
    
    /**
     * JWT权限系统诊断接口
     */
    @GetMapping("/jwt-diagnosis")
    public Result<Map<String, Object>> diagnoseJwt() {
        log.info("JWT权限系统诊断");
        
        Map<String, Object> diagnosis = new HashMap<>();
        
        // 基础信息
        diagnosis.put("timestamp", java.time.LocalDateTime.now());
        diagnosis.put("message", "JWT权限系统诊断");
        
        // 提示用户如何测试
        Map<String, String> instructions = new HashMap<>();
        instructions.put("step1", "登录获取token：POST /api/user/login (用户名:admin, 密码:123456)");
        instructions.put("step2", "复制返回的token字段");
        instructions.put("step3", "在请求头中添加：Authorization: Bearer {token}");
        instructions.put("step4", "访问需要权限的接口：GET /api/user/articles/stats");
        
        diagnosis.put("testInstructions", instructions);
        
        Map<String, String> commonIssues = new HashMap<>();
        commonIssues.put("issue1", "权限数据库表未初始化 - 执行 src/main/resources/sql/permission_schema.sql");
        commonIssues.put("issue2", "用户未登录或token已过期");
        commonIssues.put("issue3", "前端未正确发送Authorization头");
        commonIssues.put("issue4", "Token格式错误（应该是 'Bearer ' + token）");
        
        diagnosis.put("commonIssues", commonIssues);
        
        // 添加一些调试建议
        Map<String, String> debugTips = new HashMap<>();
        debugTips.put("tip1", "查看控制台日志，寻找拦截器的DEBUG信息");
        debugTips.put("tip2", "确认浏览器开发者工具中Network面板的请求头");
        debugTips.put("tip3", "检查localStorage中是否存在token");
        
        diagnosis.put("debugTips", debugTips);
        
        return Result.success("JWT诊断信息", diagnosis);
    }
    
    /**
     * 权限测试接口 - 需要USER角色
     */
    @GetMapping("/permission-test")
    @com.example.demo.annotation.RequiresRole("USER")
    public Result<Map<String, Object>> permissionTest(
            jakarta.servlet.http.HttpServletRequest request) {
        
        log.info("权限测试接口被访问");
        
        Map<String, Object> result = new HashMap<>();
        
        // 获取拦截器设置的用户信息
        Object userId = request.getAttribute("currentUserId");
        Object username = request.getAttribute("currentUsername");
        Object roles = request.getAttribute("currentUserRoles");
        Object permissions = request.getAttribute("currentUserPermissions");
        
        result.put("success", true);
        result.put("message", "权限验证通过");
        result.put("userId", userId);
        result.put("username", username);
        result.put("roles", roles);
        result.put("permissions", permissions);
        result.put("timestamp", java.time.LocalDateTime.now());
        
        // 检查Authorization头
        String authHeader = request.getHeader("Authorization");
        result.put("authHeader", authHeader != null ? authHeader.substring(0, Math.min(authHeader.length(), 20)) + "..." : "null");
        
        log.info("权限测试结果 - 用户ID: {}, 用户名: {}", userId, username);
        
        return Result.success("权限测试通过", result);
    }
    
    /**
     * 无权限测试接口 - 不需要任何权限
     */
    @GetMapping("/no-permission-test")
    public Result<Map<String, Object>> noPermissionTest(
            jakarta.servlet.http.HttpServletRequest request) {
        
        log.info("无权限测试接口被访问");
        
        Map<String, Object> result = new HashMap<>();
        result.put("message", "这是无权限要求的接口");
        result.put("timestamp", java.time.LocalDateTime.now());
        
        // 检查是否有用户信息（拦截器不应该设置）
        Object userId = request.getAttribute("currentUserId");
        result.put("hasUserInfo", userId != null);
        
        return Result.success("无权限测试", result);
    }
}
